package cn.bqjr.platform.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect  
@Component  
public class DataSourceAop {  
  
  
    public static final Logger logger = LoggerFactory.getLogger(DataSourceAop.class);  
  
  
    @Before("execution(* cn.bqjr.platform.read.service.impl.*.*(..)) ")  
    public void setReadDataSourceType(JoinPoint point) {  
    	logger.info("dataSource == >：come in从库读的db");   
    	Object[] args = point.getArgs();
  	  	String dbKey = args[0].toString(); 
        if(dbKey.equals("dcn01")){
      	  DataSourceContextHolder.setDataSourceType(DataSourceType.read1.getType());  
      	  logger.info("dataSource == >: 从库读的db1 ");
        }else{  	   
      	  DataSourceContextHolder.setDataSourceType(DataSourceType.read2.getType());
      	  logger.info("dataSource == >: 从库读的db2 ");
        }       
        logger.info("dataSource == >: get out从库读的db");
        logger.info("dataSource切换到：Read");  
    }
    
    @After("execution(* cn.bqjr.platform.read.service.impl.*.*(..)) ")
    public void readAfterReturning() throws Throwable {
        DataSourceContextHolder.clearDataSourceType();
        logger.info("=====> clear dataSource aop ");
    }
  
  
    @Before("execution(* cn.bqjr.platform.write.service.impl.*.*(..)) ")  
    public void setWriteDataSourceType(JoinPoint point) {  
    	logger.info("dataSource == >：come in主库写的db");   
    	Object[] args = point.getArgs();
  	  	String dbKey = args[0].toString(); 
        if(dbKey.equals("dcn01")){
      	  DataSourceContextHolder.setDataSourceType(DataSourceType.write1.getType());  
      	  logger.info("dataSource == >: 主库写的db1 ");
        }else{  	   
      	  DataSourceContextHolder.setDataSourceType(DataSourceType.write2.getType());
      	  logger.info("dataSource == >: 主库写的db2 ");
        }       
        logger.info("dataSource == >: get out主库写的db");
        logger.info("dataSource切换到：Write");  
    }  
    
    @After("execution(* cn.bqjr.platform.write.service.impl.*.*(..)) ")
    public void writeAfterReturning() throws Throwable {
        DataSourceContextHolder.clearDataSourceType();
        logger.info("=====> clear dataSource aop ");
    }
}  